<!--搜索结果页组件-->
<template>
  <div class="all">
    <div class="content">
      <div class="left">
        <DropDownList @sort-changed="handleSortChange"></DropDownList>
      </div>
      <div class="right">
        <div class="searchbox">
          <SearchBox @search="handleSearch"></SearchBox>
        </div>
        <div class="count">共找到{{ this.total }}篇包含{{ this.searchText }}的文章</div>
        <SearchResult :articles="this.articles"></SearchResult>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          layout="total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import service from "@/utils/service";
import DropDownList from "@/components/DropDownList.vue";
import SearchBox from "@/components/SearchBox.vue";
import SearchResult from "@/components/SearchResult.vue";

export default {
  components: {
    DropDownList,
    SearchBox,
    SearchResult,
  },
  data() {
    return {
      selectedSort: "发布日期",//默认是发布日期是排序字段
      searchText: "", //当前组件的搜索框，不是页头的搜索框
      currentPage: 1,//当前页数
      total: 0,//存储查询结果总数
      articles: []//存储查询到的文章

    };
  },
  methods: {
    //排序字段改变
    handleSortChange(sortOption) {
      console.log("排序选项改变为", sortOption);
      this.selectedSort = sortOption;
      //搜索字段改变，触发重新搜索
      this.search();
      // 将排序字段添加到当前的query参数中
      this.$router.push({query: {...this.$route.query, sort: sortOption}});
    },
    //当搜索按钮点击后，父组件获取搜索关键字
    handleSearch(searchText) {
      console.log("非页头搜索框搜索关键字为", searchText);
      this.currentPage = 1;
      this.searchText = searchText;

    },
    //分页事件
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      //分页改变，触发重新搜索
      this.search();
      // 将页码添加到当前的query参数中
      this.$router.push({query: {...this.$route.query, page: newPage}});
    },

    //搜索请求
    async search() {
      try {
        const apiUrl = "/articles/search";
        const response = await service.get(apiUrl, {
          params: {
            keyword: this.searchText,
            sortFiled: this.selectedSort,
            page: this.currentPage
          }

        });

        if (response.data.code === 20041) {
          this.articles = response.data.data.articles;
          this.total = response.data.data.total;//总数
        }

      } catch {
        console.log('搜索错误');

      }

    }
  },
  watch: {
    //监听路由参数的变化
    "$route.query.key": {
      handler(newVal, oldVal) {
        console.log("路由参数 key 发生了变化");
        console.log("新值：", newVal);
        console.log("旧值：", oldVal);

        this.searchText = newVal;
      },
      immediate: true, // 这个选项可以在组件创建时立即触发一次 watch 回调
    },
    "$route.query.page": {
      handler(newVal, oldVal) {
        console.log("路由参数 page 发生了变化");
        console.log("新值：", newVal);
        console.log("旧值：", oldVal);

        this.currentPage = Number(newVal);
        this.search();
      },
      immediate: true, // 这个选项可以在组件创建时立即触发一次 watch 回调
    },
    "$route.query.sort": {
      handler(newVal, oldVal) {
        console.log("路由参数 sort 发生了变化");
        console.log("新值：", newVal);
        console.log("旧值：", oldVal);

        if(newVal !== undefined){
          this.selectedSort = newVal;

        }else {
          this.selectedSort = '发布日期';
        }


        this.search();
      },
      immediate: true, // 这个选项可以在组件创建时立即触发一次 watch 回调
    },

    //监听搜索文本的变化,当搜索文本变了，所以排序字段归为默认
    searchText: {
      handler(newText, oldText) {
        // searchText 发生变化时执行的操作
        console.log("搜索文本变化");
        console.log("新值", newText);
        console.log("旧值", oldText);
        // searchText 发生变化时更新路由参数
        if (newText && oldText === undefined) {
          console.log('此时为刷新或从其他页面进入');
          if (this.$route.query.page) {
            this.currentPage = Number(this.$route.query.page);
            console.log('从query中获取的页数为', this.currentPage);
          } else {
            this.currentPage = 1;
          }

          if (this.$route.query.sort) {
            this.selectedSort = this.$route.query.sort;
            console.log('从query中获取的sort字段为', this.selectedSort);
          } else {
            this.selectedSort = '发布日期';
          }

          if (this.$route.query.key) {
            this.searchText = this.$route.query.key;
            console.log("从query中获取的key为", this.searchText);
          }
          this.search();
        } else {
          // 设置页数和排序为默认值
          this.currentPage = 1;
          this.selectedSort = "发布日期";
          this.search();
        }
      },
      immediate: true, // 立即执行一次回调
    },
  },

};
</script>


<style scoped>
.all {
  width: 100%;
  margin: 0 auto;
}

.left {
  float: left;
  width: 200px;
  padding-left: 1%;
  padding-top: 1%;
}

.right {
  float: left;
  width: 1100px;
  height: auto;
  margin-left: 1%;
  margin-top: 1%;
  margin-bottom: 1%;
  padding-left: 1%;
  padding-top: 1%;
  padding-bottom: 1%;
  border: 1px solid #c3bebe;
}

.searchbox {
  width: 100%;
  padding-bottom: 1%;
}

.count {
  background-color: antiquewhite;
  line-height: 40px;
  padding-left: 5px;
  width: 98%;
}

.content {
  display: flex;
  justify-content: center;
}
</style>
